// cloud/database.js - 云数据库操作封装
class TaskDatabase {
  constructor() {
    this.db = wx.cloud.database()
    this.taskCollection = this.db.collection('tasks')
  }

  // 添加任务
  async addTask(taskData) {
    try {
      const result = await this.taskCollection.add({
        data: {
          ...taskData,
          createTime: this.db.serverDate(),
          updateTime: this.db.serverDate()
        }
      })
      return result
    } catch (error) {
      console.error('添加任务失败:', error)
      throw error
    }
  }

  // 更新任务
  async updateTask(taskId, updateData) {
    try {
      const result = await this.taskCollection.doc(taskId).update({
        data: {
          ...updateData,
          updateTime: this.db.serverDate()
        }
      })
      return result
    } catch (error) {
      console.error('更新任务失败:', error)
      throw error
    }
  }

  // 删除任务
  async deleteTask(taskId) {
    try {
      const result = await this.taskCollection.doc(taskId).remove()
      return result
    } catch (error) {
      console.error('删除任务失败:', error)
      throw error
    }
  }

  // 获取用户任务列表
  async getUserTasks(userId, date = null) {
    try {
      let query = this.taskCollection.where({
        userId: userId
      })

      if (date) {
        query = query.where({
          date: date
        })
      }

      const result = await query.orderBy('createTime', 'desc').get()
      return result.data
    } catch (error) {
      console.error('获取任务列表失败:', error)
      throw error
    }
  }

  // 获取任务详情
  async getTaskDetail(taskId) {
    try {
      const result = await this.taskCollection.doc(taskId).get()
      return result.data
    } catch (error) {
      console.error('获取任务详情失败:', error)
      throw error
    }
  }

  // 获取任务统计
  async getTaskStats(userId, startDate, endDate) {
    try {
      const result = await this.taskCollection.where({
        userId: userId,
        createTime: this.db.command.gte(startDate).and(this.db.command.lte(endDate))
      }).get()
      
      const tasks = result.data
      const stats = {
        total: tasks.length,
        completed: tasks.filter(task => task.completed).length,
        totalTime: tasks.reduce((sum, task) => sum + (task.duration || 0), 0),
        avgTime: 0
      }
      
      const completedTasks = tasks.filter(task => task.completed && task.duration)
      if (completedTasks.length > 0) {
        stats.avgTime = Math.round(stats.totalTime / completedTasks.length)
      }
      
      return stats
    } catch (error) {
      console.error('获取任务统计失败:', error)
      throw error
    }
  }
}

module.exports = TaskDatabase